#include "storage.h"

Storage::Storage(string fname, unsigned int pLen, unsigned int numOP,unsigned int fileLen)
{
	fileLength = fileLen;
	numOfPieces = numOP;
	pieceLen = pLen;
	char *fn = (char*)fname.c_str();
	fd = open(fn,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
	fileopen = (fd==-1) ? false : true;
	int ret;
	if(!fileopen)
	{
		cout<<"error opening file"<<endl;
		exit(1);
	}
	else
	{
		ret = ftruncate(fd,fileLen);
		if(ret==-1)
		{
			cout<<"failed to create file large enough"<<endl;
			exit(1);
		}
	}

	if(ret==-1)
		cout<<"error creating file"<<endl;
}

Storage::~Storage()
{
//	cout<<"storage deleted"<<endl;
	close(fd);
}

bool Storage::fileOpen()
{
	return fileopen;
}

int Storage::store(int piece,unsigned length,char *data)
{
	int pos = piece*pieceLen;
	lseek(fd,pos,SEEK_SET);
	int bytes = write(fd,data,length);
	return bytes;
}

void Storage::GetPiece(unsigned char *buf, unsigned piece, unsigned len)
{
	int pos = piece * pieceLen;
	lseek(fd,pos,SEEK_SET);
	read(fd,buf,len);
	return;
}

